package com.atguigu.gmall.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: 李旭
 * @create: 2021-09-08 10:20
 *
 *  远程调用拦截器
 *
 **/
//@Component //实例化的注解  所有微服务都有远程调用拦截器 死板
public class FeignInterceptor implements RequestInterceptor {


    //远程调用拦截器方法
    //远程调用之前 先调用拦截器  再发出远程调用请求
    //RequestTemplate : 马上要发出的远程调用的这个请求
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //1:当前请求   任意位置如何获取当前请求对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if(null != servletRequestAttributes){
            HttpServletRequest request = servletRequestAttributes.getRequest();
            if(null != request){
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                if(!StringUtils.isEmpty(userId)){
                    //2：马上发出的远程调用请求
                    requestTemplate.header("userId",userId);
                }
                if(!StringUtils.isEmpty(userTempId)){
                    //2：马上发出的远程调用请求
                    requestTemplate.header("userTempId",userTempId);
                }
            }
        }

    }
}
